import { defineStore } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
export const useTodoStore = defineStore('todo', {
  state: () => ({
    /** @type {{ text: string, id: number, isFinished: boolean }[]} */
    todos: [
      {
        id: 1,
        text: '1111',
        isFinished: false
      },
      {
        id: 2,
        text: '2222',
        isFinished: false
      },
      {
        id: 3,
        text: '333333',
        isFinished: false
      }
    ],
    /** @type{ {  text:string ,id:number , isFinished:boolean }}   */
    todo: {
      id: -1,
      text: '',
      isFinished: false
    },
    /** @type {'all' | 'finished' | 'unfinished'} */
    filter: 'all',
    // 类型将自动推断为 number
    nextId: 5,
    index: 1,
    // 类型将自动推断为 boolean
    dialogFormVisible: false,
    cardTitle: 'abcd'
  }),
  getters: {
    /**
     * @returns {{ text: string, id: number, isFinished: boolean }[]}
     */
    filteredTodos(state) {
      if (this.filter === 'all') return state.todos
      else if (this.filter === 'finished') {
        return this.todos.filter((todo) => todo.isFinished)
      } else if (this.filter === 'unfinished') {
        return this.todos.filter((todo) => !todo.isFinished)
      }
    }
  },
  actions: {
    handleFinis(index, row) {
      row.isFinished = true
    },
    delete(index) {
      ElMessageBox.confirm(
        ` ${this.todos[index].text}   will permanently delete the file. Continue? `,
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          this.todos.splice(index, 1)
          ElMessage({
            type: 'success',
            message: 'Delete completed'
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: 'Delete canceled'
          })
        })
    },
    handleAdd() {
      this.showDialog()
      this.todo.id = -1
    },
    loaddata() {
      this.todos.push({ text: 'text', id: this.index++, isFinished: false })
    },
    showDialog() {
      this.dialogFormVisible = true
    },
    save() {
      console.log(this.todo)
      if (this.todo.id === -1) {
        this.todo.id = this.nextId++
        // 数据隔离
        this.todos.push(JSON.parse(JSON.stringify(this.todo)))
      } else {
        const temp = JSON.parse(JSON.stringify(this.todo))
        this.todos.splice(this.index, 1, temp)
      }

      this.dialogFormVisible = false
    },
    handleEdit(index, row) {
      this.showDialog()
      this.index = index
      this.todo = JSON.parse(JSON.stringify(row))
    }
  }
})
